package com.algorithm.code.stack;

/**
 * @description 采用链表实现栈
 * @program: sudy
 * @author: kukuxiahuni
 * @create: 2020-01-25 16:00
 **/
public class ListStack<T> implements BaseStack<T> {

    public static void main(String[] args) {
        ListStack<Integer> listStack = new ListStack<>();
        for (int i = 0; i < 20; ++i) {
            listStack.push(i);
        }

        System.out.println(listStack.peek());
        System.out.println(listStack.pop());
        for (int i = 0; i< 3; ++i) {
            System.out.println(listStack.pop());
        }

        System.out.println(listStack.peek());
    }

    /**
     * 头结点
     */
    private final Node<T> head = new Node<>(null, null);


    /**
     * @Description: 链表节点
     * @Param:
     * @return:
     * @Author: kukuxiahuni
     * @Date: 2020/1/25
     */
    private final static class Node<T> {
        T value;
        Node<T> next;

        public Node(T value, Node<T> next) {
            this.value = value;
            this.next = next;
        }
    }

    @Override
    public boolean isEmpty() {
        return head.next == null;
    }

    @Override
    public T pop() {
        if (isEmpty()) {
            return null;
        }

        Node<T> value = head.next;
        head.next = head.next.next;

        return value.value;
    }

    @Override
    public T peek() {
        if (isEmpty()) {
            return null;
        }
        return this.head.next.value;
    }

    @Override
    public void push(T value) {

        if (value == null) {
            return;
        }

        Node<T> node = new Node<>(value, null);
        node.next = head.next;
        head.next = node;
    }
}
